<?php

namespace App\Core\Database;

use Illuminate\Support\Facades\Cache;
use Redis;

class Cacher
{
    public static $enable = true;

    protected $query;

    protected $prefix = '';

    protected $expire = 3600;

    public function __construct($query)
    {
        $this->query = $query;
    }

    public static function disable()
    {
        static::$enable = false;
    }

    public static function isEnable()
    {
        return static::$enable;
    }

    public function getExpire()
    {
        return $this->expire;
    }

    public function setExpire($seconds = 3600)
    {
        $this->expire = $seconds;
    }

    public function getPrefix()
    {
        return $this->prefix;
    }

    public function setPrefix($prefix = '')
    {
        $this->prefix = $prefix;
    }

//    abstract public function get();

//    abstract public function put();

    public function del($ids = [])
    {
        Cache::del($ids);
    }

    /**
     * 获取缓存的键名
     * @param $value
     * @return string
     */
    protected function getCacheKey($value)
    {
        return str_replace(
            ['TABLE', 'VALUE'],
            [$this->query->getTableName(), $value],
            $this->query->getCacheKeyFormat()
        );
    }

    // 写入redis的时候需要使用redis锁
    public function put($data)
    {
        foreach ($data as $key => $value) {
            Redis::set($key, $value);
            // RedisLock::lock($key, function($key, $value) {
            //     Redis::put($key, $value);
            // });
        }
    }

    public function lock($name, $seconds = 0, $owner = null)
    {
        return new RedisLock(app('redis'), $this->prefix.$name, $seconds, $owner);
    }

    protected function releaseLock($name, $owner)
    {
        return $this->lock($name, 0, $owner);
    }

    protected function pack($data)
    {
        return gzcompress(json_encode($data));
    }

    protected function unpack($data)
    {
        return json_decode(gzuncompress($data), true);
    }

}
